package cn.tsingmo.otproxy.client;

import cn.tsingmo.otproxy.security.AuthenticationHandler;
import cn.tsingmo.otproxy.security.DecryptionHandler;
import cn.tsingmo.otproxy.security.EncryptionHandler;
import cn.tsingmo.otproxy.security.EncryptionService;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

/**
 * 客户端Channel初始化器
 */
public class ClientInitializer extends ChannelInitializer<SocketChannel> {
    private final String targetHost;
    private final int targetPort;
    private final EncryptionService encryptionService;

    public ClientInitializer(String targetHost, int targetPort) {
        this.targetHost = targetHost;
        this.targetPort = targetPort;
        this.encryptionService = new EncryptionService();
    }

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        // 添加帧解码器和编码器，处理TCP粘包/拆包问题
        pipeline.addLast(new LengthFieldBasedFrameDecoder(1024 * 1024, 0, 4, 0, 4));
        pipeline.addLast(new LengthFieldPrepender(4));

        // 字符串编解码器
        pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
        pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));

        // 安全相关处理器
        pipeline.addLast(new AuthenticationHandler());
        pipeline.addLast(new DecryptionHandler(encryptionService));
        pipeline.addLast(new EncryptionHandler(encryptionService));

        // 客户端业务逻辑处理器
        pipeline.addLast(new ClientConnectionHandler(targetHost, targetPort));
    }
}